<template>
  <div>
    <van-sticky>
      <van-nav-bar
        title="绑定信息"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </van-sticky>
    <!-- 表格 -->
    <vxe-table
      v-if="bindList && bindList.length"
      border="inner"
      size="mini"
      :data="bindList"
    >
      <!-- <vxe-column type="seq" title="" width="40"></vxe-column> -->
      <!-- 姓名 -->
      <vxe-column :field="'userName'" :title="'姓名'" width="80" />
      <!-- 身份证 -->
      <vxe-column :field="'cardNo'" :title="'身份证'" />
      <!-- 删除按钮 -->
      <vxe-column width="65" :title="'操作'">
        <template #default="{ row }">
          <a
            href="javascript:void(0)"
            :class="{ disable: apis.delete['status'] === 1 }"
            @click.stop="apis.delete['status'] === 0 && deleteBindInfo(row)"
            >删除</a
          >
        </template>
      </vxe-column>
    </vxe-table>
    <van-list v-if="bindList && bindList.length" style="margin-top: 10px">
      <van-row style="height: 34px; line-height: 34px">
        <van-col span="24" style="text-align: center"
          ><a
            href="javascript:void(0)"
            class="continue"
            @click.stop="toBindInfo"
            >继续绑定</a
          ></van-col
        >
      </van-row>
    </van-list>
    <div v-else>
      <van-empty>
        <template #description>
          暂未绑定信息，<a href="javascript:void(0)" @click.stop="toBindInfo"
            >去绑定</a
          >
        </template>
      </van-empty>
    </div>
    <!-- 下拉弹窗 -->
    <van-popup v-model:show="showPopup" round position="bottom">
      <van-cascader
        v-model="bindInfo.kinshipValue"
        title="请选择"
        :options="relationDict"
        :field-names="{ text: 'dictValue', value: 'dictKey' }"
        @close="showPopup = false"
        @change="selectConditionChange(bindInfo.kinshipValue)"
      />
    </van-popup>
    <!-- 去增加绑定信息 -->
    <PopupCpt ref="refPopupCpt">
      <van-sticky>
        <van-nav-bar
          title="绑定信息"
          left-text="返回"
          left-arrow
          @click-left="close"
        />
      </van-sticky>
      <div>
        <van-form @submit="submitBindInfo">
          <van-field
            v-model="bindInfo.kinshipText"
            is-link
            disabled
            clearable
            class="el-form-item"
            label="亲属昵称"
            :clear-trigger="'always'"
            placeholder="请选择亲属昵称"
            :rules="[{ required: true, message: '请选择亲属昵称' }]"
            @update:model-value="selectConditionChange"
            @click="showPopup = true"
          />
          <van-field
            v-model="bindInfo.refPhone"
            class="el-form-item"
            name="refPhone"
            label="手机号"
            placeholder="手机号"
            :rules="[{ validator: patPhone }]"
          />
          <van-cell-group class="msgBtn">
            <van-field
              v-model="bindInfo.smsCode"
              class="el-form-item"
              name="smsCode"
              center
              clearable
              label="短信验证码"
              placeholder="请输入短信验证码"
            >
              <template #button>
                <van-button
                  class="msg-text"
                  size="small"
                  type="primary"
                  :class="{ display: phoneState.msgKey }"
                  @click="handleSend"
                >
                  {{ msgText }}
                </van-button>
              </template>
            </van-field>
          </van-cell-group>
          <div class="btns">
            <van-button
              round
              block
              type="primary"
              :disabled="apis.submit.status === 1"
              :loading="apis.submit.status === 1"
              native-type="submit"
              >提 交</van-button
            >
          </div>
        </van-form>
      </div>
    </PopupCpt>
  </div>
</template>
<script lang="ts">
import axios from '../../../../api/axios'
import { getMsgCode } from '../../../../api/login/login'
import PopupCpt from '/@/components/PopupCpt.vue'
import { Toast, Notify } from 'vant'
import { useStore } from '/@/store'
import { defineComponent, ref, reactive, onBeforeMount } from 'vue'

export default defineComponent({
  components: { PopupCpt },
  setup() {
    const { commit, state } = useStore()
    const refPopupCpt: any = ref(null) // 弹出框的$refs值
    const bindList: any = ref([])
    const bindInfo: any = reactive({
      kinshipText: '', // 亲属昵称
      kinshipValue: '', // 亲属昵称实际值
      refPhone: '', // 手机号码
      smsCode: '', // 验证码
    })
    const relationDict: any = ref([])
    let showPopup: any = ref(false)
    const phoneState = {
      msgText: '发送验证码',
      msgKey: false,
      msgTime: 60,
    }
    const msgText = ref('发送验证码')
    const patPhone = (val: any) => {
      if (!new RegExp(/^1\d{10}$/).test(val)) {
        return '请输入正确的手机号'
      }
      return ''
    }
    // 接口请求url、请求状态、参数等信息
    const apis: any = ref({
      // 提交绑定接口
      submit: {
        url: '/api/blade-user/userRelation/saveOrUpdate',
        type: 'post', // 接口请求类型
        status: 0, // 接口请求状态，0=未请求，1=请求中
        getParams(params: any) {
          // 参数
          return {
            tenantId: state.user.tenantId,
            userId: state.user.userId,
            refId: params.kinshipValue,
            ...params,
          }
        },
      },
      // 删除绑定信息的接口
      delete: {
        url: '/api/blade-user/userRelation/remove',
        type: 'post', // 接口请求类型
        status: 0, // 接口请求状态，0=未请求，1=请求中
        getParams(params: any) {
          // 参数
          return {
            tenantId: state.user.tenantId,
            id: params.id,
            ids: params.id,
            isDelete: '1',
          }
        },
      },
    })
    onBeforeMount(async () => {
      loadBindList() // 获取绑定信息
      getRelationDictData() // 获取所有家长关系的字典数据
    })
    // 获取绑定信息
    async function loadBindList() {
      let { data } = await axios.get(
        `/api/blade-user/userRelation/list?tenantId=${state.user.tenantId}&userId=${state.user.userId}&userIds=${state.user.userId}`
      )
      bindList.value = data.data || []
    }
    async function getRelationDictData() {
      let { data } = await axios.get(
        `/api/blade-system/dict/dictionary?code=kinship`
      )
      relationDict.value = data.data || []
    }
    // 调用接口
    async function callApi(
      apiOp: {
        status: number
        url: string
        type: string
        getParams: Function | null
      },
      params: any,
      callback: Function | null // 成功的回调
    ) {
      console.log('callApi', JSON.stringify(params))
      if (typeof apiOp['getParams'] === 'function') {
        params = apiOp['getParams'](params)
      }
      apiOp['status'] = 1 // 请求中
      axios[apiOp['type']](apiOp['url'], params)
        .then(({ data }) => {
          if (data.success) {
            // 请求成功
            if (typeof callback === 'function') {
              callback(params)
            }
          } else {
            Toast(data.message || '请求失败')
          }
        })
        .finally(() => {
          apiOp['status'] = 0 // 恢复未请求状态
        })
    }
    // 显示
    function show() {
      refPopupCpt.value.show()
    }
    // 隐藏
    function close() {
      refPopupCpt.value.close()
    }
    return {
      refPopupCpt,
      bindList,
      bindInfo,
      apis,
      patPhone,
      relationDict,
      showPopup,
      show,
      close,
      phoneState,
      msgText,
      handleSend() {
        let msg = patPhone(bindInfo.refPhone)
        if (msg) {
          Notify({ type: 'warning', message: msg })
          return
        }
        if (phoneState.msgKey) return
        msgText.value = phoneState.msgTime + '秒后重发'
        phoneState.msgKey = true
        axios.post('/api/blade-user/userRelation/checkUserByPhone', {
          refPhone: bindInfo.refPhone,
        })
        const time = setInterval(() => {
          phoneState.msgTime--
          msgText.value = phoneState.msgTime + '秒后重发'
          if (phoneState.msgTime == 0) {
            phoneState.msgTime = 60
            msgText.value = '发送验证码'
            phoneState.msgKey = false
            clearInterval(time)
          }
        }, 1000)
      },
      // 去绑定
      toBindInfo() {
        show() // 显示弹框
      },
      // 下拉框的field数据变化
      selectConditionChange(value: any) {
        showPopup.value = false
        if (!value) {
          bindInfo.kinshipText = ''
          bindInfo.kinshipValue = ''
          return
        }
        let dict = relationDict.value.find(
          (dict: any) => dict['dictKey'] === value
        )
        bindInfo.kinshipText = dict['dictValue']
      },
      // 删除绑定
      deleteBindInfo(item: any) {
        callApi(apis.value.delete, item, () => {
          // 成功的回调
          Toast('删除成功！')
          loadBindList()
        })
      },
      // 提交绑定
      submitBindInfo() {
        callApi(apis.value.submit, bindInfo, () => {
          // 成功的回调
          Toast('绑定成功！')
          close()
          loadBindList()
        })
      },
      onClickLeft() {
        history.back()
      },
    }
  },
})
</script>

<style lang="less" scoped>
.el-form-item {
  margin-bottom: 12px;
  opacity: 0.8;
  border-radius: 5px;
}
.msgBtn {
  opacity: 0.8;
  border-radius: 5px;
}
.msg-text.display {
  color: #ccc;
}
.btns {
  margin: 30px 10px 20px;
  text-align: center;
}
a.disable {
  color: #999;
  cursor: not-allowed;
  pointer-events: none;
}

.continue {
  font-size: 13px;
}
</style>
